import axios from "axios";
import { message } from "antd";
import history from "@/router/config";
import type {
  AxiosInstance,
  InternalAxiosRequestConfig,
  AxiosResponse
} from "axios";
import { getStoreItem, setStoreItem } from "@/util/storage";
import { removeStoreItem } from "@/util/storage";
import { store } from "@/store/index";
// 创建实例时配置默认值
const instance: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASEURL,
  timeout: 5000
});

// 添加请求拦截器
instance.interceptors.request.use(
  function (config: InternalAxiosRequestConfig) {
    // 在发送请求之前做些什么
    const Authorization = getStoreItem("token");
    if (Authorization)
      config.headers.Authorization = "Bearer" + " " + Authorization;
    return config;
  },
  function (error: any) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

const errCode = {
  401: "token过期",
  403: "没有权限",
  404: "请求地址不存在",
  500: "服务器内部错误",
  502: "网关错误"
};
instance.interceptors.response.use(
  function (response: AxiosResponse) {
    if (response.data.statusCode !== 200) {
      const datamesg =
        response.data?.errorInfo ||
        response.data?.msg ||
        errCode[response.data?.statusCode] ||
        "请求出错了";
      message.error(datamesg);
      /* 未登录跳转登录界面，清空用户信息 */
      if (response.data.statusCode === 401) {
        store.dispatch({ type: "user/setUser", payload: {} });
        removeStoreItem(["token", "userInfo"]);
        history.navigate("/login");
      }
      return Promise.reject(response.data);
    }
    if (response.headers.authorization) {
      setStoreItem("token", response.headers.authorization.split(" ")[1]);
    }
    return response.data;
  },
  function (error: any) {
    message.error(errCode[error.status]);
    return Promise.reject(error);
  }
);

export default instance;
